import Vue from 'vue'
import VueRouter from "vue-router"
import VueResource from "vue-resource"
import routes from './routes'
import Config from './config.js'
import MintUI from 'mint-ui'
import {Button,Field} from 'mint-ui'
import Header from './header.vue'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import VueClipboard from 'vue-clipboard2'
import VueCookies from 'vue-cookies'

Vue.use(VueClipboard);

//开启debug模式
Vue.config.debug = true;
Vue.use(VueResource);
Vue.use(VueRouter);
Vue.use(MintUI);
Vue.use(Button);
Vue.use(Field);
Vue.prototype.utilHelper = Config;
Vue.config.productionTip = false;
Vue.use(VueCookies);


// mount with global
Vue.use(VueAwesomeSwiper)

const router = new VueRouter({
    base: __dirname,
    routes
});

const appAssistant = Config.appAssistant;
const appAgency = Config.appAgency;

Vue.component("Header",Header);

Vue.directive('res',function(el,binding){
        if( !window.sessionStorage.getItem(appAssistant+"_resources")){
            el.style.display = 'none';
            return;
        }
        // var res = window.sessionStorage.getItem("userAuthResources").split(',');
        var res = window.sessionStorage.getItem(appAssistant+"_resources").split(',');
        if(res == null){
            el.style.display = 'none';
            return;
        }

        for(var i=0;i<res.length;i++){
            if(binding.value.code == res[i]){
                el.style.display = '';
                break
            }else{
                el.style.display = 'none';
            }
        }
    }
);

Vue.directive('title', {
    inserted: function (el, binding) {
        document.title = el.dataset.title
    }
});

Vue.prototype.tourist = function (){
    const loginType = window.sessionStorage.getItem('loginType')?window.sessionStorage.getItem('loginType'):appAgency;
    //若为游客则弹出绑定对话框
    var userRole =  window.sessionStorage.getItem(loginType + "_userRole");
    if(!userRole){
    	layer.confirm('登陆信息已过期，',{
    		btn:['去登陆'],
			title:false,
			shade:[0]
		},function(index){
            layer.close(index);
            router.push('login');
        });
        return true;
	}
    if(userRole && userRole == '-1'){
        layer.confirm('您尚未绑定公司！',{
                btn :['以后再说','去绑定'],
                title: false,
                closeBtn: 0, //不显示关闭按钮
                shade: [0]
            },function(index){
                layer.close(index);
			},
            function(index){
                router.push({path:'/bindCompany'});
                layer.close(index);
            }
        );
        return true;
    }
}


router.beforeEach(({meta,path}, from, next) => {
  const loginType = window.sessionStorage.getItem('loginType')?window.sessionStorage.getItem('loginType'):appAgency;
  if (appAgency == loginType) {
    //当返回到顶层时,将当前路径设置为下一个返回路径
    var isLogin = window.sessionStorage.getItem(appAgency +"_isLogin");
    if("/register" == path || "/forgetPassword" == path|| "/assistantForgetPassword" == path){
      return next();
    }
    if("/agencyIndex" == path || "/" == path || "/agency" == path || "/login" == path){
      //当返回至 /app 时,往前走一步,跳转到首页
      if("/agency" == path){
        window.history.forward(1);
      }
      if("/login" == path && (isLogin==true || isLogin=="true")){
        return next({
          path: '/agencyIndex'
        });
      }
      history.pushState(null, null, document.URL);
    }

    if((!isLogin || isLogin == 'null' || isLogin==false || isLogin=="false")&& path !== '/login') {
      return next({
        path: '/login'
      })
    }
    next();
  } else {
    var isLogin = window.sessionStorage.getItem(appAssistant+"_isLogin");
    if("/forgetPassword" == path||"/assistantForgetPassword"==path){
      return next();
    }
    if("/assistantIndex" == path || "/" == path || "/assistant" == path || "/login" == path){
      //当返回至 /app 时,往前走一步,跳转到首页
      if("/assistant" == path && isLogin==true){
        window.history.forward(1);
      }
      if("/login" == path && (isLogin==true || isLogin=="true")){
        return next({
          path: '/assistantIndex'
        });
      }
      history.pushState(null, null, document.URL);
    }

    if((!isLogin || isLogin == 'null' || isLogin==false || isLogin=="false")&& path !== '/login') {
      return next({
        path: '/login'
      })
    }
    next();
    if(isLogin == 'true'){
      var url = Config.apiUrl + "/api/getUserAuthList";
      var body = {};
      body.params = {resourcesType:'2',resourcesOrigin:'1',resourcesLevel:'1',userId:window.sessionStorage.getItem(appAssistant+"_userId"),companyUuid:window.sessionStorage.getItem("companyUuid")};
      Vue.http.post(url, body).then((response) => {
        var data = response.body.resData;
        var result=data.result;
        var errorMsg = data.resultMsg;
        if(result=="1"){
          window.sessionStorage.setItem(appAssistant+"_resources",data.resourcesList);
        }
      });
    }
  }
});

Vue.http.interceptors.push((request, next) => {
  const loginType = window.sessionStorage.getItem('loginType')?window.sessionStorage.getItem('loginType'):appAgency;
  if (appAgency == loginType) {
    //绑定登陆ID
    var userId=window.sessionStorage.getItem(appAgency + "_userId");
    var companyUuid = window.sessionStorage.getItem("companyUuid");
    var requestBody=request.getBody();
    if (requestBody && requestBody.params) {
      if (userId && request.url.indexOf("getLogo") == -1 && request.url.indexOf("login") == -1 && request.url.indexOf("regist") == -1
          && request.url.indexOf("sendValidateCodeForPwd") == -1 && request.url.indexOf("sendVerificationCode") == -1
          && request.url.indexOf("getCompanyByPhone") == -1) {
        requestBody.params.userId=userId;
      }
      requestBody.params.loginType = appAgency;
      requestBody.params.companyUuid = companyUuid;
      request.body=requestBody;
    }

    request.headers.set('loginType',loginType);
    request.headers.set('userId',userId);
    request.headers.set("companyUuid",companyUuid);
    //request.headers.set('companyUuid', companyUuid);
    next((response) => {
      //验证登陆
      var isLogin = window.sessionStorage[appAgency+"_isLogin"];
      if(isLogin == "true") {
      	if(!response.ok){
			window.sessionStorage.removeItem(appAgency+"_isLogin");
			window.sessionStorage.removeItem(appAgency+"_userId");
			layer.closeAll();
			router.replace({
				path: '/login'
			});
			return;
		}
        if(typeof(response.body) == 'string') {
          var responseBody = JSON.parse(response.body);
          var result = responseBody.result;
          if(result && result == "-1") {
            router.replace({
              path: '/login'
            });
            return;
          }
        }
      }
    });
  } else {
    var userId=window.sessionStorage.getItem(appAssistant+"_userId");
    var requestBody=request.getBody();
    if (requestBody && requestBody.params) {
      if (userId && request.url.indexOf("getLogo") == -1 && request.url.indexOf("login") == -1
      && request.url.indexOf("getCompanyByAssistantPhone") == -1) {
        requestBody.params.userId=userId;
      }
      if(request.url.indexOf("loginOut")!=-1){
        requestBody.params.userId=userId;
      }
      requestBody.params.loginType = appAssistant;
      request.body=requestBody;
    }
    request.headers.set('loginType',loginType);
    request.headers.set('userId',userId);
    next((response) => {
      //验证登陆
      var isLogin = window.sessionStorage[appAssistant+"_isLogin"];
      if(isLogin == "true") {
      	 if(!response.ok){
      	 	layer.closeAll();
			window.sessionStorage.removeItem(appAssistant+"_isLogin");
			window.sessionStorage.removeItem(appAssistant+"_userId");
			router.replace({
				path: '/login'
			});
			return;
		}
        if(typeof(response.body) == 'string') {
          var responseBody = response.body;
          var result = responseBody.result;
          if(result && result == "-1") {
            router.replace({
              path: '/login'
            });
            return;
          }
        }
      }
    });
  }
});

const app = new Vue({
    router: router
}).$mount('#app');

export default {
    Header
}


